package cc.booku.owlbox.VideoPlayer;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videoplayer.listener.OnVideoViewStateChangeListener;
import com.dueeeke.videoplayer.player.IjkVideoView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.base.TBaseAdapter;
import com.timmy.tdialog.list.TListDialog;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import cc.booku.owlbox.loadSqlite.DatabaseHelper;
import cc.booku.owlbox.m3u8Tomp4.Constant;
import cc.booku.owlbox.m3u8Tomp4.DownloadListener;
import cc.booku.owlbox.m3u8Tomp4.M3u8DownloadFactory;
import jaygoo.library.m3u8downloader.M3U8Downloader;
import jaygoo.library.m3u8downloader.M3U8DownloaderConfig;
import jaygoo.library.m3u8downloader.OnM3U8DownloadListener;
import jaygoo.library.m3u8downloader.bean.M3U8Task;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static cc.booku.owlbox.m3u8Tomp4.Constant.FILESEPARATOR;


/**
 * 播放器演示
 * Created by Devlin_n on 2017/4/7.
 */

//file:///storage/emulated/0/OwlDatabase/video/670bd858f8c50783f52770123c1b02e8/local.m3u8

public class PlayerActivity extends AppCompatActivity {

    private static final String TAG = "PlayerActivity";

    private VideoView mVideoView;
    //解密后的片段
    //所有ts片段下载链接
    private final Set<File> finishedFiles = new ConcurrentSkipListSet<>(Comparator.comparingInt(o -> Integer.parseInt(o.getName().replace(".xyz", ""))));
    private final String dirPath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "VideoDownload";
    private ProgressBarView progressBarView;
    private TextView player_title_data, player_blurb_data, tv_label, love_collect, down_info, ic_x2, tv_skip;
    private final List<TVSeries_C> tvSeries_cList = new ArrayList<TVSeries_C>();
    private HorizontalListView tvseries_list;
    private String tv_series = null;
    private String tv_url = null;
    private HorizontalListView player_labelid;
    private SQLiteDatabase db;
    private DatabaseHelper helper;
    private Button bt_qq;
    private TextView tv_moretv, tv_discuss;
    private ImageView player_module_download, player_module_x2, player_module_collect, player_module_share, player_module_projectionscreen, ic_down;
    private TextView iv_player_back, iv_player_come;
    M3U8Task[] taskList = new M3U8Task[1];
    private boolean isimageview = false;

    private final List<player_discuss_class> player_discuss_classList = new ArrayList<player_discuss_class>();
    private GridView player_discuss_list;

    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        CrashHandler crashHandler = CrashHandler.getInstance();
//        crashHandler.init(getApplicationContext());
        setContentView(R.layout.activity_player);
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        mVideoView = findViewById(R.id.player);

        ic_down = findViewById(R.id.ic_down);
        progressBarView = (ProgressBarView) findViewById(R.id.progress_bar_view);
        player_title_data = (TextView) findViewById(R.id.player_title_data);
        player_blurb_data = (TextView) findViewById(R.id.player_blurb_data);
        player_discuss_list = (GridView) findViewById(R.id.player_discuss_list);
        tv_label = (TextView) findViewById(R.id.tv_label);
        tvseries_list = (HorizontalListView) findViewById(R.id.tvseries_list);
        player_labelid = (HorizontalListView) findViewById(R.id.player_labelid);
        love_collect = (TextView) findViewById(R.id.love_collect);
        down_info = (TextView) findViewById(R.id.down_info);
        tv_discuss = (TextView) findViewById(R.id.tv_discuss);
        Bundle bundle = getIntent().getExtras();
        assert bundle != null;
        String vod_name = bundle.getString("vod_name");
        String vod_play_url = bundle.getString("vod_play_url");
        tv_moretv = (TextView) findViewById(R.id.tv_moretv);
        tv_moretv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                // tvsJSON(vod_play_url);
                JSONArray jsArr = JSONObject.parseArray(tvsJSON(vod_play_url));
                List<String> list = JSONObject.parseArray(jsArr.toJSONString(), String.class);
                bottomListDialog(list);
            }
        });
        tv_skip = (TextView) findViewById(R.id.tv_skip);
        tv_skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long pos = mVideoView.getCurrentPosition();
                pos = 120000; // milliseconds
                mVideoView.seekTo(pos);
                setProgress(1000);
                tv_skip.setVisibility(View.GONE);
                // Toast.makeText(PlayerActivity.this, "快退05秒", Toast.LENGTH_SHORT).show();
            }
        });
        tvSkipGone();
        iv_player_back = (TextView) findViewById(R.id.iv_player_back);
        iv_player_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long pos = mVideoView.getCurrentPosition();
                pos -= 10000; // milliseconds
                mVideoView.seekTo(pos);
                setProgress(1000);
                Toast.makeText(PlayerActivity.this, pos / 1000 + "秒", Toast.LENGTH_SHORT).show();
            }
        });
        iv_player_come = (TextView) findViewById(R.id.iv_player_come);
        iv_player_come.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long pos = mVideoView.getCurrentPosition();
                pos += 15000; // milliseconds
                mVideoView.seekTo(pos);
                setProgress(1000);
                Toast.makeText(PlayerActivity.this, pos / 1000 + "秒", Toast.LENGTH_SHORT).show();
            }
        });

        player_blurb_data.post(new Runnable() {
            @Override
            public void run() {
                boolean b = isTextView(player_blurb_data);
                if (b) {
                    ic_down.setVisibility(View.VISIBLE);
                } else {
                    ic_down.setVisibility(View.GONE);
                }
            }
        });


        ic_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isimageview) {
                    ic_down.setBackgroundResource(R.drawable.ic_up);
                    player_blurb_data.setMaxLines(10);
                    player_title_data.setMaxLines(10);
                    isimageview = true;
                } else {
                    ic_down.setBackgroundResource(R.drawable.ic_down);
                    player_blurb_data.setMaxLines(2);
                    player_title_data.setMaxLines(1);
                    isimageview = false;
                }
            }
        });


        player_module_share = (ImageView) findViewById(R.id.player_module_share);

        player_module_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                long pos = ijkVideoView.getCurrentPosition();
//                pos += 15000; // milliseconds
//                ijkVideoView.seekTo(pos);
//                setProgress(3000);
                Toast.makeText(PlayerActivity.this, "待开发", Toast.LENGTH_SHORT).show();
            }
        });
        bt_qq = (Button) findViewById(R.id.bt_qq);
        bt_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    SystemUtil.joinQQGroup(PlayerActivity.this, "WZXjv7I736JKIJ48YTlIfCuLvHlWTx0a");
                } catch (Exception e) {
                    //异常处理
                    bt_qq.setText("打开失败！点击重试~");
                }
            }
        });

        /** 初始化数据 */
        initData();
        /** 实例化数据库 */
        initsqlite();
        //收藏初始化
        fundown_init();
        /** 首次进入播放页面 初始化评论 */
        discuss_init2();

        funlove_init();

        // 历史记录
        funhistory();
        ic_x2 = (TextView) findViewById(R.id.ic_x2);
        player_module_download = (ImageView) findViewById(R.id.player_module_download);
        player_module_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (progressBarView.getVisibility() == View.VISIBLE) {
                    progressBarView.setVisibility(View.GONE);

                } else if (progressBarView.getVisibility() == View.GONE) {
                    progressBarView.setVisibility(View.VISIBLE);
                }
                onDownload();
//                Message msg = new Message();
//                msg.what = 24;
//                episodehandler.sendMessage(msg);//用activity中的handler发送消息
//                Intent intent = getIntent();
//                String downurl = intent.getStringExtra("vod_play_url");
//                if(tv_url!=null) {
//                    m3u8down(player_title_data.getText().toString().trim(),tv_url);
//                }else m3u8down(player_title_data.getText().toString().trim(),downurl);


                //跳转到FileScannerActivity打开指定文件
//                Intent intent = new Intent(PlayerActivity.this, RecyclerViewActivity.class);
//                startActivity(intent);
            }
        });
        player_module_projectionscreen = (ImageView) findViewById(R.id.player_module_projectionscreen);
        player_module_projectionscreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(PlayerActivity.this, "待开发", Toast.LENGTH_SHORT).show();
            }
        });
        player_module_x2 = (ImageView) findViewById(R.id.player_module_x2);
        player_module_x2.setOnClickListener(new View.OnClickListener() {
            final int count = 1;
            int click = count;

            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {

                switch (click) {
                    case 1:
                        mVideoView.setSpeed(0.5f);
                        click++;
                        ic_x2.setText("0.5f");
                        break;
                    case 2:
                        mVideoView.setSpeed(0.75f);
                        click++;
                        ic_x2.setText("0.75f");
                        break;
                    case 3:
                        mVideoView.setSpeed(1.0f);
                        click++;
                        ic_x2.setText("1.0f");
                        break;
                    case 4:
                        mVideoView.setSpeed(1.5f);
                        click++;
                        ic_x2.setText("1.5f");
                        break;
                    case 5:
                        mVideoView.setSpeed(2.0f);
                        click = count;
                        ic_x2.setText("2.0f");
                        break;
                }

            }
        });


        tv_discuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                new TDialog.Builder(getSupportFragmentManager())
                        .setLayoutRes(R.layout.tdialog_evaluate)
                        .setScreenWidthAspect(PlayerActivity.this, 1.0f)
                        .setGravity(Gravity.BOTTOM)
                        .addOnClickListener(R.id.btn_evluate)
                        .setOnViewClickListener(new OnViewClickListener() {
                            @Override
                            public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                                //EditText editText = viewHolder.getView(R.id.editText);
                                EditText editText = viewHolder.getView(R.id.editText);
                                String content = editText.getText().toString().trim();

                                String ConfigFiles_json = FileoOperations.readAssetsTxt(PlayerActivity.this, "TxtData/ConfigFiles");
                                JSONObject objsd = JSONObject.parseObject(ConfigFiles_json);
                                String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
                                String DecryptionAddress = Decrypt.RsaDecrypt(PlayerActivity.this, ciphertext);
                                String adddiscuss = objsd.getString("ADDDISCUSS");//发表评论
                                String discusslist = objsd.getString("DISCUSSLIST");//发表评论
                                //读取文件
                                String user_id = "1";
                                String comment_name = "匿名用户";
                                //player_discuss_editid.getText().toString();//评论信息
                                Bundle bundle = getIntent().getExtras();
                                String vod_class = bundle.getString("vod_class");
                                String[] labelDate = vod_class.split("\\#");//影片id

                                Log.d("++++++++++++", labelDate[3] + "---" + labelDate[4]);

                                String url = DecryptionAddress + adddiscuss + "comment_rid=" + labelDate[4] + "&user_id=" + user_id + "&comment_name=" + comment_name + "&comment_content=" + content + "";

                                try {
                                    //请求，将数据写入
                                    HttpADDdiscuss(url);
                                } catch (Exception e) {
                                    Log.i("response===========>", url);
                                }
                                // 获取评论数据进行展示
                                init_discuss_data(DecryptionAddress + discusslist + labelDate[4]);
                                // 评论完成刷新
                                player_discuss_classList.clear();
//                                // 获取评论数据进行展示
//                                init_discuss_data(DecryptionAddress + discusslist + labelDate[4]);

                                tDialog.dismiss();
                            }
                        })
                        .create()
                        .show();


            }
        });
        player_module_collect = (ImageView) findViewById(R.id.player_module_collect);
        player_module_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Toast.makeText(VideoPlayerActivity.this, "待开发", Toast.LENGTH_SHORT).show();
                //新页面接收数据
                Bundle bundle = getIntent().getExtras();
                assert bundle != null;
                String vod_class = bundle.getString("vod_class");
                String vod_score = bundle.getString("vod_score");
                String vod_name = bundle.getString("vod_name");
                String vod_add_time = bundle.getString("vod_add_time");
                String vod_play_url = bundle.getString("vod_play_url");
                String vod_pic = bundle.getString("vod_pic");
                String vod_value_add = bundle.getString("vod_value_add");

                if (love_collect.getText().toString().equals("已收藏")) {

                    db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
                    db.delete("loveTable", "vod_name=?", new String[]{vod_name});

                    db.close();

                    love_collect.setText("已取消");
                } else {


                    db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
                    //使用 ContentValues 来对要添加的数据进行组装
                    ContentValues valuec = new ContentValues();
                    // 开始组装第一条数据
                    valuec.put("vod_score", vod_score);
                    valuec.put("vod_name", vod_name);
                    valuec.put("vod_class", vod_class);
                    valuec.put("vod_pic", vod_pic);
                    valuec.put("vod_play_url", vod_play_url);
                    valuec.put("vod_add_time", vod_add_time);
                    valuec.put("vod_value_add", vod_value_add);
                    // 插入第一条数据love_
                    db.insert("loveTable", null, valuec);
                    valuec.clear();
                    db.close();

                    love_collect.setText("已收藏");


                }


            }
        });


        /*
         * 在线播放$https://dadi-bo.com/share/1RD5u25bCHULZpME
         * $$$在线播放$https://dadi-bo.com/20181211/K9hoRxY8/index.m3u8
         *
         * */


        //如果存在$就使用$分割
        assert vod_play_url != null;
        if (vod_play_url.contains("$")) {
//Log.d(vod_play_url, "---###---" + vod_play_url);
            if (vod_play_url.contains("#")) {

                Log.d(vod_play_url, "---###---" + "应该是个剧集");
            } else {
                String[] str1 = vod_play_url.split("\\$");//拆分需要加正则，查看是否存在不需要

                init_ijkplayer(str1[1], vod_name);
            }
        }//否则直接传给webview
        else {
            init_ijkplayer(vod_play_url, vod_name);
        }

//            StandardVideoController controller = new StandardVideoController(this);
//        System.out.println(vod_play_url);
//            //String title = intent.getStringExtra(IntentKeys.TITLE);
//            controller.setTitle(vod_name);
//            //intent.getStringExtra("url")
//            ijkVideoView.setUrl(vod_play_url);
//            ijkVideoView.setVideoController(controller);
//            ijkVideoView.start();

        //播放状态监听
        mVideoView.addOnVideoViewStateChangeListener(mOnVideoViewStateChangeListener);


    }

    private boolean isTextView(TextView textView) {
        float m = textView.getPaint().measureText(textView.getText().toString());
        float n = 3 * (textView.getWidth() - textView.getPaddingRight() - textView.getPaddingLeft());
        return m > n;
    }

    private void bottomListDialog(List<String> list) {
        new TListDialog.Builder(getSupportFragmentManager())
                .setScreenHeightAspect(PlayerActivity.this, 0.6f)
                .setScreenWidthAspect(PlayerActivity.this, 1.0f)
                .setGravity(Gravity.BOTTOM)
                .setAdapter(new TBaseAdapter<String>(R.layout.item_bottom_list_text, list) {

                    protected void onBind(BindViewHolder holder, int position, String s) {
                        //处理一下显示,和最后点击没有任何关系
                        //s是json，取指定就行
                        JSONObject obj = JSONObject.parseObject(s);
                        String result = obj.getString("TVSeries");
                        holder.setText(R.id.tv, result);

                    }
                })
                .setOnAdapterItemClickListener(new TBaseAdapter.OnAdapterItemClickListener<String>() {

                    public void onItemClick(BindViewHolder holder, int position, String s, TDialog tDialog) {
                        // Toast.makeText(PlayerActivity.this, "click:" + s, Toast.LENGTH_SHORT).show();
                        JSONObject obj = JSONObject.parseObject(s);
                        String tv_series1 = obj.getString("TVSeries");
                        String tv_url1 = obj.getString("TVUrl");

                        Message msg = new Message();
                        msg.what = 15;
                        Bundle bundle = new Bundle();
                        bundle.putString("videourl", tv_url1);
                        bundle.putString("episodetitle", tv_series1);
                        msg.setData(bundle);
                        episodehandler.sendMessage(msg);

                        tDialog.dismiss();
                    }
                })
//                .setOnDismissListener(new DialogInterface.OnDismissListener() {
//                    @Override
//                    public void onDismiss(DialogInterface dialog) {
//                        Toast.makeText(getActivity(), "setOnDismissListener 回调", Toast.LENGTH_SHORT).show();
//                    }
//                })
                .create()
                .show();
    }


    //等待刷新函数
    private void tvSkipGone() {
        //Toast.makeText(PlayerActivity.this, "编辑成功", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //finish();
                //AnimationUtils.showAndHiddenAnimation(tv_skip, AnimationUtils.AnimationState.STATE_HIDDEN,2000);
                tv_skip.setVisibility(View.GONE);
            }
        }, 20000);
        // onCreate(null);//调用此方法刷新页面

    }

    public void initsqlite() {
        Log.d(TAG, "initsqlite实例化SQLiteOpenHelper的子类对象开始..............");
        //5.实例化SQLiteOpenHelper的子类对象-MyDataBaseHelper
        helper = new DatabaseHelper(this, "dbdate", null, R.string.db_version);//dbName数据库名
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
    }

    private boolean funhistory_init() {

        boolean state = false;
        //历史初始化
        Bundle bundle = getIntent().getExtras();
        assert bundle != null;
        String vod_name = bundle.getString("vod_name");
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select vod_name from collectTable where vod_name = vod_name ", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String title_str = cursor.getString(0);
            state = title_str.equals(vod_name);
            // Log.i("System.out", title_str);
        }

        return state;
    }

    private void funhistory() {
        if (funhistory_init()) {
            Log.i("System.out------", "已经存在不添加");
        } else {
            //新页面接收数据
            Bundle bundle = getIntent().getExtras();
            assert bundle != null;
            String vod_class = bundle.getString("vod_class");
            String vod_score = bundle.getString("vod_score");
            String vod_name = bundle.getString("vod_name");
            String vod_add_time = bundle.getString("vod_add_time");
            String vod_play_url = bundle.getString("vod_play_url");
            String vod_pic = bundle.getString("vod_pic");
            String vod_value_add = bundle.getString("vod_value_add");

            db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
            //使用 ContentValues 来对要添加的数据进行组装
            ContentValues valuec = new ContentValues();
            // 开始组装第一条数据
            valuec.put("vod_score", vod_score);
            valuec.put("vod_name", vod_name);
            valuec.put("vod_class", vod_class);
            valuec.put("vod_pic", vod_pic);
            valuec.put("vod_play_url", vod_play_url);
            valuec.put("vod_add_time", vod_add_time);
            valuec.put("vod_value_add", vod_value_add);
            // 插入第一条数据love_
            db.insert("collectTable", null, valuec);
            valuec.clear();
            db.close();

            // love_collect.setText("已收藏");
        }

    }

    private void discuss_init2() {
        String ConfigFiles_json = FileoOperations.readAssetsTxt(PlayerActivity.this, "TxtData/ConfigFiles");
        JSONObject objsd = JSONObject.parseObject(ConfigFiles_json);
        String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
        String DecryptionAddress = Decrypt.RsaDecrypt(PlayerActivity.this, ciphertext);
        String adddiscuss = objsd.getString("ADDDISCUSS");//发表评论
        String discusslist = objsd.getString("DISCUSSLIST");//发表评论
        // 获取评论数据进行展示

        Bundle bundle = getIntent().getExtras();
        String vod_class = bundle.getString("vod_class");
        String[] labelDate = vod_class.split("\\#");//影片id
        Log.d(TAG, "展示评论URL" + DecryptionAddress + discusslist + labelDate[4]);

        init_discuss_data(DecryptionAddress + discusslist + labelDate[4]);
    }

    private void fundown_init() {
        //收藏初始化
        Bundle bundle = getIntent().getExtras();
        String vod_name = bundle.getString("vod_name");
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
        Cursor cursor = db.rawQuery("select vod_name from downTable where vod_name = vod_name ", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String title_str = cursor.getString(0);
            if (title_str.equals(vod_name)) {
                down_info.setText("已下载");
            }
        }
    }

    private void funlove_init() {
        //收藏初始化
        Bundle bundle = getIntent().getExtras();
        String vod_name = bundle.getString("vod_name");
        db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
        Cursor cursor = db.rawQuery("select vod_name from loveTable where vod_name = vod_name ", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String title_str = cursor.getString(0);
            if (title_str.equals(vod_name)) {
                //love_state = true;//已经收藏
                //  love_img.setImageResource(R.drawable.ic_love_yes);

                love_collect.setText("已收藏");
                //Log.i("System.out------", "love_state=false");
            }
            // Log.i("System.out", title_str);
        }
    }

    public void init_ijkplayer(String URL, String title) {


        StandardVideoController controller = new StandardVideoController(this);
        //String title = intent.getStringExtra(IntentKeys.TITLE);
        controller.setTitle(title);
        //intent.getStringExtra("url")
        mVideoView.setUrl(URL);
        // ijkVideoView.setPlayerFactory(IjkPlayerFactory.create());
        mVideoView.setVideoController(controller);
        mVideoView.release();
    }

    private void initData() {
        Log.d(TAG, "初始化数据开始方法名：initData");
        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        String vod_class = bundle.getString("vod_class");
        String vod_score = bundle.getString("vod_score");
        String vod_name = bundle.getString("vod_name");
        String vod_add_time = bundle.getString("vod_add_time");
        String vod_play_url = bundle.getString("vod_play_url");
        String vod_value_add = bundle.getString("vod_value_add");

        String[] str1 = vod_value_add.split("\\$");
        String[] str2 = str1[1].split("\\\n");
        //这个是视频信息
        player_blurb_data.setText(str2[1]);
        player_title_data.setText(vod_name);
        tv_label.setText(vod_class);
        split_vod_class(vod_class);

        Message msg = new Message();
        msg.what = 5;
        bundle = new Bundle();
        bundle.putString("vod_play_url", vod_play_url);  //往Bundle中存放数据
        msg.setData(bundle);//mes利用Bundle传递数据
        episodehandler.sendMessage(msg);//用activity中的handler发送消息

        Log.d(TAG, "initData初始化数据结束");

    }


    private void split_vod_class(String str) {

        //"#"+vod_class+"#"+vod_remarks+"#"+vod_year+"#"+vod_area+"#"+vod_lang
//        player_label_class labelclass = new player_label_class();
        String[] labelDate = str.split("\\#");
//            for (int i = 0; i < labelDate.length; i++) {
//                labelclass.setStr_class(labelDate[i]);
//        } player_label_classlist.add(labelclass);
        ArrayList<String> Listt = new ArrayList<String>();
        Listt.add(labelDate[0]);
        Listt.add(labelDate[1]);
        Listt.add(labelDate[2]);
        Listt.add(labelDate[3]);
        Listt.add(labelDate[4]);
        //Listt.add(labelDate[5]);
        //创建Adapter对象
        labelAdapter adapter = new labelAdapter(this, Listt);

        //把Adapter对象添加到视图ListView中
        player_labelid.setAdapter(adapter);

        //ListView的监听(条目)
        player_labelid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {


            }
        });


    }


    private String tvsJSON(String full_url) {

        String full_url1 = "[{" + "\"TVSeries\":\"" + full_url + "\"}]";
        String full_url2 = full_url1.replace("#", "\"},{\"TVSeries\":\"");
        String full_url3 = full_url2.replace("$", "\",\"TVUrl\":\"");
        //JSONObject json = JSONObject.fromObject(str)

        return full_url3;
    }

    public void url_split(final String full_url) {


        //搜索是否存在# 存在就遍历
        //不存在就安按照$取数

        //拆分 full_url = purl

        boolean status = full_url.contains("#");
        TVSeries_C tvSeries_c;
        if (status) {


//            System.out.println("存在");
//            //做成json
//            String full_url1 = "[{" + "\"TVSeries\":\"" + full_url + "\"}]";
//            String full_url2 = full_url1.replace("#", "\"},{\"TVSeries\":\"");
//            String full_url3 = full_url2.replace("$", "\",\"TVUrl\":\"");
//            //JSONObject json = JSONObject.fromObject(str)
//
//            System.out.println(full_url3);//已经显示出来了


            String full_url3 = tvsJSON(full_url);


            ByteArrayInputStream stream = new ByteArrayInputStream(full_url3.getBytes());
            StringBuilder stringBuffer = new StringBuilder();
            String str = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            try {
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //03.使用fastJson解析Json、
            List<TVSeries_C> gatherc = JSON.parseArray(stringBuffer.toString(), TVSeries_C.class);
            for (TVSeries_C pp : gatherc) {
                tvSeries_c = new TVSeries_C();
                String tvUrl = pp.getTVUrl();
                String tvSeries = pp.getTVSeries();

                tvSeries_c.setTVUrl(tvUrl);
                tvSeries_c.setTVSeries(tvSeries);

                //pfilmclass.setParea(carea);
                //将结果添加到对象集合中
                tvSeries_cList.add(tvSeries_c);
            }
            Message msg = new Message();
            msg.what = 9;
            episodehandler.sendMessage(msg);//用activity中的handler发送消息

        } else {
            System.out.println("不存在");
            //不存在就 按照$拆分成数组，第一[0]就写到控件[1]写到链接
            //Toast.makeText(this, "该影片无其他剧集", Toast.LENGTH_SHORT).show();
            String full_url1 = "[{" + "\"TVSeries\":\"" + full_url + "\"}]";
            String full_url3 = full_url1.replace("$", "\",\"TVUrl\":\"");
            //JSONObject json = JSONObject.fromObject(str)

            System.out.println(full_url3);//已经显示出来了

            ByteArrayInputStream stream = new ByteArrayInputStream(full_url3.getBytes());
            StringBuilder stringBuffer = new StringBuilder();
            String str = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(stream));
            try {
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //03.使用fastJson解析Json、
            List<TVSeries_C> gatherc = JSON.parseArray(stringBuffer.toString(), TVSeries_C.class);
            for (TVSeries_C pp : gatherc) {
                tvSeries_c = new TVSeries_C();
                String tvUrl = pp.getTVUrl();
                String tvSeries = pp.getTVSeries();

                tvSeries_c.setTVUrl(tvUrl);
                tvSeries_c.setTVSeries(tvSeries);

                //pfilmclass.setParea(carea);
                //将结果添加到对象集合中
                tvSeries_cList.add(tvSeries_c);
            }
            Message msg = new Message();
            msg.what = 9;
            episodehandler.sendMessage(msg);//用activity中的handler发送消息


        }

    }

    @SuppressLint("HandlerLeak")
    private final Handler episodehandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 5:

                    String vod_play_url5 = msg.getData().getString("vod_play_url");

                    url_split(vod_play_url5);

                    break;

                case 9:

                    CollectData((ArrayList<TVSeries_C>) tvSeries_cList);
                    //bottomListDialog(tvSeries_cList);
                    break;
                case 15:
                    Bundle bundle = getIntent().getExtras();
                    String vod_name = bundle.getString("vod_name");
                    // String episodetitle = bundle.getString("episodetitle");
                    tv_url = msg.getData().getString("videourl");//接受msg传递过来的参数
                    tv_series = msg.getData().getString("episodetitle");//接受msg传递过来的参数
                    init_ijkplayer(tv_url, vod_name + "-" + tv_series);
                    player_title_data.setText(tv_series + "-" + vod_name);
                    tv_skip.setVisibility(View.VISIBLE);
                    tvSkipGone();
                    break;
                case 22:
                    click_discuss_data((ArrayList<player_discuss_class>) player_discuss_classList);
                    break;

                case 24:
                    Intent intent = getIntent();
                    String downurl = intent.getStringExtra("vod_play_url");
                    if (tv_url != null) {
                        m3u8down(player_title_data.getText().toString().trim(), tv_url);
                    } else m3u8down(player_title_data.getText().toString().trim(), downurl);
                    break;
                case 80:
                    //private String vod_score, vod_name, vod_class, vod_pic, vod_play_url, vod_add_time,vod_value_add;
                    String downvod_score = msg.getData().getString("vod_score");//接受msg传递过来的参数
                    String downvod_name = msg.getData().getString("vod_name");//接受msg传递过来的参数
                    String downvod_class = msg.getData().getString("vod_class");//接受msg传递过来的参数
                    String downvod_pic = msg.getData().getString("vod_pic");//接受msg传递过来的参数
                    String downvod_play_url = msg.getData().getString("vod_play_url");//接受msg传递过来的参数
                    String downvod_add_time = msg.getData().getString("vod_add_time");//接受msg传递过来的参数
                    String downvod_value_add = msg.getData().getString("vod_value_add");//接受msg传递过来的参数


                    db = helper.getWritableDatabase();//获取到了 SQLiteDatabase 对象
                    //使用 ContentValues 来对要添加的数据进行组装
                    ContentValues valuedown = new ContentValues();
                    // 开始组装第一条数据
                    valuedown.put("vod_score", downvod_score);
                    valuedown.put("vod_name", downvod_name);
                    valuedown.put("vod_class", downvod_class);
                    valuedown.put("vod_pic", downvod_pic);
                    valuedown.put("vod_play_url", downvod_play_url);
                    valuedown.put("vod_add_time", downvod_add_time);
                    valuedown.put("vod_value_add", downvod_value_add);
                    // 插入第一条数据love_
                    db.insert("downTable", null, valuedown);
                    valuedown.clear();
                    db.close();
                    break;
            }
        }
    };


    static class labelAdapter extends BaseAdapter implements ListAdapter {


        private ArrayList<String> player_label_classList;
        private Context context;

        public labelAdapter(Context context, ArrayList<String> subClassList) {
            super();
            this.player_label_classList = subClassList;
            this.context = context;

        }

        @Override
        public int getCount() {
            return player_label_classList.size();
        }

        @Override
        public Object getItem(int i) {
            return player_label_classList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @SuppressLint({"WrongConstant", "InflateParams"})
        @Override

        public View getView(int position, View contextView, ViewGroup parent) {

            // 获取指定索引值的数据
            String string = player_label_classList.get(position);

            if (contextView == null) {
                // 通过LayoutInflater 类的 from 方法 再 使用 inflate()方法得到指定的布局
                // 得到ListView中要显示的条目的布局
                LayoutInflater from = LayoutInflater.from(context);
                contextView = from.inflate(R.layout.player_label_class_item, null);
                // 从要显示的条目布局中 获得指定的组件
                Temp.tv = (TextView) contextView.findViewById(R.id.vod_class);
            }


            // 设置数值
            Temp.tv.setText(string);

            // 返回布局
            return contextView;
        }

        private static final class ViewHolder {
            TextView vod_class = null;

            public ViewHolder(TextView vod_class) {
                this.vod_class = vod_class;
            }

        }

        //静态内部类,保证不一直查找此对象(优化)
        static class Temp {
            static TextView tv;
        }
    }


    private TVSeries_A tvSeriesA;

    private void CollectData(ArrayList<TVSeries_C> tvSeries_cList) {

        tvSeriesA = new TVSeries_A(R.layout.htvseries_item, this, tvSeries_cList);
        //tvSeriesA = new TVSeries_A(R.layout.tvseries_item, this, tvSeries_cList);
        tvseries_list.setAdapter(tvSeriesA);
        tvseries_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                TextView tv_series = (TextView) view.findViewById(R.id.tv_series);//电影名称
                TextView tv_url = (TextView) view.findViewById(R.id.tv_url);//类型

                String tv_series1 = tv_series.getText().toString();
                //gather_url1 = null;
                String tv_url1 = tv_url.getText().toString();
                //tv_series.setTextColor(Color.parseColor("#00C5CD"));


                // TODO Auto-generated method stub
                Message msg = new Message();
                msg.what = 15;
                Bundle bundle = new Bundle();
                bundle.putString("videourl", tv_url1);
                bundle.putString("episodetitle", tv_series1);
                msg.setData(bundle);
                episodehandler.sendMessage(msg);
//
//                Log.i("test======", "===gather_name1===" + tv_series1 + "===gather_url1===" + tv_url1);


            }
        });

    }

    //******************************************************************************************


    public void click_discuss_data(ArrayList<player_discuss_class> player_discuss_classList) {


        player_discuss_Adapter player_discuss_AdapterA = new player_discuss_Adapter(R.layout.player_discuss_item, this, player_discuss_classList);

        player_discuss_list.setAdapter(player_discuss_AdapterA);
        player_discuss_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


//                final TextView comment_name = (TextView) view.findViewById(R.id.player_discuss_comment_nameid);
//                final TextView comment_time = (TextView) view.findViewById(R.id.player_discuss_comment_timeid);
//                final TextView comment_content = (TextView) view.findViewById(R.id.player_discuss_comment_contentid);
//                final TextView comment_value = (TextView) view.findViewById(R.id.player_discuss_comment_valueid);
//
//
//
//                final String comment_names = comment_name.getText().toString();
//                final String comment_times = comment_time.getText().toString();
//                final String comment_contents = comment_content.getText().toString();
//                String comment_values = comment_value.getText().toString();


            }
        });


        player_discuss_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, final View view,
                                           final int i, long l) {
//                final TextView comment_value = (TextView) view.findViewById(R.id.player_discuss_comment_valueid);
//                String comment_values = comment_value.getText().toString();
//                final TextView comment_name = (TextView) view.findViewById(R.id.player_discuss_comment_nameid);
//                final String[] valusedata = comment_values.split("\\#");
//                pulldownlist(valusedata[0], comment_name.getText().toString());
                return true;
            }
        });

    }

    private void HttpADDdiscuss(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);
                Log.i("response===========>", res);

            }
        });

    }


    public player_discuss_class discuss_classC;

    // 根据对应URL获取评论
    public void init_discuss_data(String Surl_file) {

        player_discuss_classList.clear();

        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(Surl_file);
        //可以省略，默认是GET请求
        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("1111", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsoninfo = response.body().string();
                ByteArrayInputStream stream = new ByteArrayInputStream(jsoninfo.getBytes());
                StringBuilder stringBuffer = new StringBuilder();
                String str = null;
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                //03.使用fastJson解析Json、


                List<player_discuss_class> discussc = JSON.parseArray(stringBuffer.toString(), player_discuss_class.class);
                for (player_discuss_class vpv : discussc) {
                    discuss_classC = new player_discuss_class();


                    String comment_id = vpv.getComment_id();
                    String comment_rid = vpv.getComment_rid();
                    String user_id = vpv.getUser_id();
                    String comment_name = vpv.getComment_name();
                    String comment_content = vpv.getComment_content();
                    String comment_time = vpv.getComment_time();
                    String comment_status = vpv.getComment_status();


//                    discuss_classC.setComment_id(comment_id);
//                    discuss_classC.setComment_rid(comment_rid);
//                    discuss_classC.setUser_id(user_id);
                    discuss_classC.setComment_name(comment_name);
                    discuss_classC.setComment_content(comment_content);
                    discuss_classC.setComment_time(comment_time);
                    discuss_classC.setComment_value(comment_id + "#" + comment_rid + "#" + user_id + "#" + comment_status);

                    player_discuss_classList.add(discuss_classC);
                }
                Message msg = new Message();
                msg.what = 22;
                episodehandler.sendMessage(msg);//用activity中的handler发送消息

            }
        });

    }


    private final OnVideoViewStateChangeListener mOnVideoViewStateChangeListener = new OnVideoViewStateChangeListener() {
        @Override
        public void onPlayerStateChanged(int playerState) {
            switch (playerState) {
                case IjkVideoView.PLAYER_NORMAL://小屏
                    break;
                case IjkVideoView.PLAYER_FULL_SCREEN://全屏
                    break;
            }
        }

        @Override
        public void onPlayStateChanged(int playState) {
            switch (playState) {
                case IjkVideoView.STATE_IDLE:
                    break;
                case IjkVideoView.STATE_PREPARING:
                    break;
                case IjkVideoView.STATE_PREPARED:
                    //需在此时获取视频宽高
                    int[] videoSize = mVideoView.getVideoSize();
                    L.d("视频宽：" + videoSize[0]);
                    L.d("视频高：" + videoSize[1]);
                    break;
                case IjkVideoView.STATE_PLAYING:
                    break;
                case IjkVideoView.STATE_PAUSED:
                    break;
                case IjkVideoView.STATE_BUFFERING:
                    break;
                case IjkVideoView.STATE_BUFFERED:
                    break;
                case IjkVideoView.STATE_PLAYBACK_COMPLETED:
                    break;
                case IjkVideoView.STATE_ERROR:
                    break;
            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVideoView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVideoView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoView.release();
    }


    @Override
    public void onBackPressed() {
//        if (!mVideoView.onBackPressed()) {
//            super.onBackPressed();
//           // PlayerActivity.this.finish();
//        }
        //PlayerActivity.this.finish();
        super.onBackPressed();
        mVideoView.onBackPressed();

    }


    int i = 0;

    public void setMirrorRotate(View view) {
        mVideoView.setMirrorRotation(i % 2 == 0);
        i++;
    }

    public void setSpeed(View view) {
        //增加倍速，试试看
        mVideoView.setSpeed(2.0f);
        Toast.makeText(PlayerActivity.this, "倍速开发中", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "点击了setSpeed....");
    }


    //视频下载

    private void onDownload() {

        //新建一个File，传入文件夹目录
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "VideoDownload");
//判断文件夹是否存在，如果不存在就创建，否则不创建
        if (!file.exists()) {
            //通过file的mkdirs()方法创建目录中包含却不存在的文件夹
            file.mkdirs();
        }


        // dirPath =  Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator+"VideoDownload";

        //Log.i("dirPath---------------",  dirPath);
        M3U8DownloaderConfig
                .build(getApplicationContext())
                .setSaveDir(dirPath)
        ;
        Intent intent = getIntent();
        String downurl = intent.getStringExtra("vod_play_url");
        if (tv_url != null) {
            initDownloadlistin(tv_url);
        } else initDownloadlistin(downurl);

    }


    private void initDownloadlistin(String downurl) {


        M3U8Task bean0 = new M3U8Task(seturl_split_av(downurl));
        taskList[0] = bean0;

        //M3U8Task mediaBean = taskList[0];
        down_info.setText("建立连接中..");

        M3U8Downloader.getInstance().setOnM3U8DownloadListener(onM3U8DownloadListener);


        //file:////storage/emulated/0/Android/data/com.shuchuwenku.cloudstood/cache/DownloadMovie/d41d8cd98f00b204e9800998ecf8427e/local.m3u8


        String url = bean0.getUrl();
        if (M3U8Downloader.getInstance().checkM3U8IsExist(url)) {
            //清空
            down_info.setText("已缓存");
        } else {
            M3U8Downloader.getInstance().download(url);
        }

    }


    private String seturl_split_av(String full_url) {

        //搜索是否存在# 存在就遍历
        //不存在就安按照$取数

        //拆分 full_url = purl

        boolean status = full_url.contains("$");
        if (status) {
            System.out.println("存在");
//            //拆分
//            String[] temp;
//            String delimeter = "在线播放$";  // 指定分割字符

//            StringUtils stringutils =  new com.shuchuwenku.cloudstood.StringUtils();
//            full_url=stringutils.substringBefore(full_url,"$");
            //temp = full_url.split(delimeter); // 分割字符串

            //full_url=full_url.substring(full_url.lastIndexOf("$"));
            int one = full_url.lastIndexOf("$");
            full_url = full_url.substring((one + 1), full_url.length());

            return full_url;

        } else {
            System.out.println("不存在");
            //不存在就 按照$拆分成数组，第一[0]就写到控件[1]写到链接
            return full_url;
        }

        //返回----第1集$https:\/\/cn1.download05.com\/hls\/20181113\/c14b3cf7e591cee087a76d2c734a0576\/1542111690\/index.m3u8
        //或者  ----HD高清$https:\/\/cn2.5311444.com\/hls\/20181028\/a81ad1d754f4af6ad6344da89fe3c0ae\/1540700636\/index.m3u8
        //return null;
    }

    private final OnM3U8DownloadListener onM3U8DownloadListener = new OnM3U8DownloadListener() {


        @Override
        public void onDownloadSuccess(M3U8Task task) {
            super.onDownloadSuccess(task);
            taskList[0] = task;
            //Log.i("onDownloadSuccess", "onDownloadSuccess");
            down_info.setText("缓存完成");

            progressBarView.setVisibility(View.GONE);


//private String vod_score, vod_name, vod_class, vod_pic, vod_play_url, vod_add_time,vod_value_add;


            String url = taskList[0].getUrl();
            String FILE_ADDRESS = M3U8Downloader.getInstance().getM3U8Path(url);//文件地址---d41d8cd98f00b204e9800998ecf8427e/local.m3u8  有问题
            //info_player.setText("进度:" + String.format("%.1f ",mediaBean.getProgress() * 100)+ "%|速度:" + mediaBean.getFormatSpeed());
            Log.e("55555555555", "FILE_ADDRESS---1==" + FILE_ADDRESS);
            // FILE_ADDRESS


            String FILE_ADDRESS1 = FILE_ADDRESS.replace("Android/data/cc.booku.owlbox/cache/", "OwlDatabase/");
            Log.e("55555555555", "FILE_ADDRESS---2==" + FILE_ADDRESS1);


            //开始合并视频
            //mergeTs();
            //删除多余的ts片段
            // deleteFiles();
            //  down_info.setText("下载完成");

            //新页面接收数据
            Bundle bundle = getIntent().getExtras();
            String vod_class = bundle.getString("vod_class");
            String vod_score = bundle.getString("vod_score");
            String vod_name = bundle.getString("vod_name");
            String vod_add_time = bundle.getString("vod_add_time");
            String vod_play_url = bundle.getString("vod_play_url");
            String vod_pic = bundle.getString("vod_pic");
            String vod_value_add = bundle.getString("vod_value_add");

            //将数据存入数据库
            Log.i("vod_pic", "vod_pic====" + vod_pic);
            Message msg = new Message();
            msg.what = 80;
            Bundle bundle2 = new Bundle();
            bundle2.putString("vod_class", vod_class);  //往Bundle中存放数据
            bundle2.putString("vod_score", vod_score);
            bundle2.putString("vod_name", vod_name);
            bundle2.putString("vod_add_time", vod_add_time);
            bundle2.putString("vod_pic", vod_pic);
            bundle2.putString("vod_value_add", vod_value_add);
            bundle2.putString("vod_play_url", "HD高清$file://" + FILE_ADDRESS1);
            msg.setData(bundle2);//mes利用Bundle传递数据
            episodehandler.sendMessage(msg);//用activity中的handler发送消息


        }


        @Override
        public void onDownloadProgress(final M3U8Task task) {
            super.onDownloadProgress(task);
            notifyChanged(task);
            //Log.i("onDownloadProgress", "onDownloadProgress");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    progressBarhandler.sendEmptyMessage((int) (task.getProgress() * 100));
                    down_info.setText(task.getFormatSpeed());
                }
            });

        }

        @Override
        public void onDownloadError(final M3U8Task task, Throwable errorMsg) {
            super.onDownloadError(task, errorMsg);
            notifyChanged(task);
            //Log.i("onDownloadError", "onDownloadError");
            down_info.setText("缓存失败");
            progressBarView.setVisibility(View.GONE);
        }

    };

    private void notifyChanged(final M3U8Task task) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                taskList[0] = task;
                //notifyDataSetChanged();
            }
        });

    }


    @SuppressLint("HandlerLeak")
    final Handler progressBarhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressBarView.setProgress(msg.what);
        }
    };


    private void m3u8down(String fILENAME, String M3U8URL) {


        M3u8DownloadFactory.M3u8Download m3u8Download = M3u8DownloadFactory.getInstance(M3U8URL);
        //设置生成目录
        m3u8Download.setDir(dirPath);
        //设置视频名称
        m3u8Download.setFileName(fILENAME);
        //设置线程数
        m3u8Download.setThreadCount(100);
        //设置重试次数
        m3u8Download.setRetryCount(100);
        //设置连接超时时间（单位：毫秒）
        m3u8Download.setTimeoutMillisecond(10000L);
        /*
        设置日志级别
        可选值：NONE INFO DEBUG ERROR
        */
        m3u8Download.setLogLevel(Constant.INFO);
        //设置监听器间隔（单位：毫秒）
        m3u8Download.setInterval(500L);
        //添加额外请求头
      /*  Map<String, Object> headersMap = new HashMap<>();
        headersMap.put("Content-Type", "text/html;charset=utf-8");
        m3u8Download.addRequestHeaderMap(headersMap);*/
        //添加监听器
        m3u8Download.addListener(new DownloadListener() {
            @Override
            public void start() {
                System.out.println("开始下载！");
            }

            @Override
            public void process(String downloadUrl, int finished, int sum, float percent) {
                System.out.println("下载网址：" + downloadUrl + "\t已下载" + finished + "个\t一共" + sum + "个\t已完成" + percent + "%");
            }

            @Override
            public void speed(String speedPerSecond) {
                System.out.println("下载速度：" + speedPerSecond);
            }

            @Override
            public void end() {
                System.out.println("下载完毕");
            }
        });
        //开始下载
        m3u8Download.start();
    }


    /**
     * 合并下载好的ts片段
     */
    private void mergeTs() {
        down_info.setText("合并中..");
        try {
            File file = new File(dirPath + FILESEPARATOR + player_title_data.getText().toString() + ".mp4");
            System.gc();
            if (file.exists())
                file.delete();
            else file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] b = new byte[4096];
            for (File f : finishedFiles) {
                FileInputStream fileInputStream = new FileInputStream(f);
                int len;
                while ((len = fileInputStream.read(b)) != -1) {
                    fileOutputStream.write(b, 0, len);
                }
                fileInputStream.close();
                fileOutputStream.flush();
            }
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除下载好的片段
     */
    @SuppressLint("SetTextI18n")
    private void deleteFiles() {
        down_info.setText("删除ts文件");
        File file = new File(dirPath);
        for (File f : file.listFiles()) {
            if (f.getName().endsWith(".xy") || f.getName().endsWith(".xyz"))
                f.delete();
        }
    }


}
